<template>
  <div id="userProfilePage">
    <a-card title="个人资料" :bordered="false">
      <a-form
        :model="userForm"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
        @finish="handleSubmit"
      >
        <!-- 头像 -->
        <a-form-item label="头像">
          <div class="avatar-wrapper">
            <a-avatar :size="120" :src="userForm.userAvatar || '/avatar.png'" />
            <div class="upload-btn">
              <a-upload
                v-model:file-list="fileList"
                name="file"
                :customRequest="handleUpload"
                :show-upload-list="false"
                accept="image/*"
              >
                <a-button>
                  <template #icon>
                    <upload-outlined />
                  </template>
                  更换头像
                </a-button>
              </a-upload>
            </div>
          </div>
        </a-form-item>

        <!-- 用户名 -->
        <a-form-item
          label="用户名"
          name="userName"
          :rules="[{ required: true, message: '请输入用户名' }]"
        >
          <a-input v-model:value="userForm.userName" placeholder="请输入用户名" />
        </a-form-item>

        <!-- 个人简介 -->
        <a-form-item label="个人简介" name="userProfile">
          <a-textarea
            v-model:value="userForm.userProfile"
            :rows="4"
            placeholder="介绍一下你自己吧"
          />
        </a-form-item>

        <!-- 账号信息（只读） -->
        <a-form-item label="账号">
          <span class="ant-form-text">{{ userInfo.userAccount }}</span>
        </a-form-item>

        <!-- 注册时间（只读） -->
        <a-form-item label="注册时间">
          <span class="ant-form-text">{{
            dayjs(userInfo.createTime).format('YYYY-MM-DD HH:mm:ss')
          }}</span>
        </a-form-item>

        <!-- 提交按钮 -->
        <a-form-item :wrapper-col="{ offset: 5, span: 16 }">
          <a-space>
            <a-button type="primary" html-type="submit" :loading="submitting">保存修改</a-button>
            <a-button @click="showPasswordModal" style="margin-left: 200px">修改密码</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 修改密码对话框 -->
    <a-modal
      v-model:visible="passwordModalVisible"
      title="修改密码"
      @ok="handlePasswordChange"
      @cancel="handlePasswordModalCancel"
      :confirmLoading="passwordChanging"
    >
      <a-form :model="passwordForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item
          label="新密码"
          name="userPassword"
          :rules="[{ required: true, message: '请输入新密码' }]"
        >
          <a-input-password v-model:value="passwordForm.userPassword" placeholder="请输入新密码" />
        </a-form-item>
        <a-form-item
          label="确认密码"
          name="checkPassword"
          :rules="[{ required: true, message: '请确认新密码' }]"
        >
          <a-input-password
            v-model:value="passwordForm.checkPassword"
            placeholder="请再次输入新密码"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import {
  editUserPasswordUsingPost,
  getLoginUserUsingGet,
  updateMyUserUsingPost,
} from '@/api/userController'
import { uploadFileUsingPost } from '@/api/fileController'
import dayjs from 'dayjs'
import { useLoginUserStore } from '@/stores/useLoginUserStore'

// 用户信息
const userInfo = ref<API.LoginUserVO>({})
const userForm = reactive<API.UserUpdateMyRequest>({
  userName: '',
  userAvatar: '',
  userProfile: '',
})

// 加载状态
const submitting = ref(false)

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getLoginUserUsingGet()
    if (res.data.code === 0 && res.data.data) {
      userInfo.value = res.data.data
      // 填充表单
      userForm.userName = res.data.data.userName
      userForm.userAvatar = res.data.data.userAvatar
      userForm.userProfile = res.data.data.userProfile
    } else {
      message.error('获取用户信息失败：' + res.data.message)
    }
  } catch (error: any) {
    message.error('获取用户信息失败：' + error.message)
  }
}

// 文件上传相关
const fileList = ref([])
const handleUpload = async (options: any) => {
  const { file, onSuccess, onError } = options
  try {
    const formData = new FormData()
    formData.append('file', file)
    const res = await uploadFileUsingPost({ biz: 'user_avatar' }, formData, file)
    if (res.data.code === 0) {
      userForm.userAvatar = res.data.data
      // 立即更新用户信息
      const updateRes = await updateMyUserUsingPost(userForm)
      if (updateRes.data.code === 0) {
        message.success('头像更新成功')
        // 重新获取用户信息以更新全局状态
        await fetchUserInfo()
        // 更新全局用户信息
        const loginUserStore = useLoginUserStore()
        await loginUserStore.fetchLoginUser()
      } else {
        message.error('头像更新失败：' + updateRes.data.message)
      }
      onSuccess()
    } else {
      onError()
      message.error('上传失败：' + res.data.message)
    }
  } catch (error) {
    onError()
    message.error('上传失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!userForm.userName?.trim()) {
    message.warning('请输入用户名')
    return
  }

  submitting.value = true
  try {
    const res = await updateMyUserUsingPost(userForm)
    if (res.data.code === 0) {
      message.success('更新成功')
      // 重新获取用户信息
      await fetchUserInfo()
    } else {
      message.error('更新失败：' + res.data.message)
    }
  } catch (error: any) {
    message.error('更新失败：' + error.message)
  } finally {
    submitting.value = false
  }
}

// 修改密码相关
const passwordModalVisible = ref(false)
const passwordChanging = ref(false)
const passwordForm = reactive({
  userPassword: '',
  checkPassword: '',
})

// 显示密码修改对话框
const showPasswordModal = () => {
  passwordModalVisible.value = true
  passwordForm.userPassword = ''
  passwordForm.checkPassword = ''
}

// 处理密码修改对话框取消
const handlePasswordModalCancel = () => {
  passwordModalVisible.value = false
  passwordForm.userPassword = ''
  passwordForm.checkPassword = ''
}

// 处理密码修改
const handlePasswordChange = async () => {
  if (!passwordForm.userPassword) {
    message.warning('请输入新密码')
    return
  }
  if (!passwordForm.checkPassword) {
    message.warning('请确认新密码')
    return
  }
  if (passwordForm.userPassword !== passwordForm.checkPassword) {
    message.warning('两次输入的密码不一致')
    return
  }

  passwordChanging.value = true
  try {
    const res = await editUserPasswordUsingPost({
      userPassword: passwordForm.userPassword,
      checkPassword: passwordForm.checkPassword,
    })
    if (res.data.code === 0) {
      message.success('密码修改成功')
      passwordModalVisible.value = false
    } else {
      message.error('密码修改失败：' + res.data.message)
    }
  } catch (error: any) {
    message.error('密码修改失败：' + error.message)
  } finally {
    passwordChanging.value = false
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
#userProfilePage {
  max-width: 800px;
  margin: 24px auto;
  padding: 0 24px;
}

.avatar-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.upload-btn {
  margin-top: 8px;
}
</style>
